<template>
  <el-dialog :title="(buttonEvent=='detail()'?'查看':buttonEvent=='edit()'?'编辑':'新增')+'架构主数据'" :before-close="close" :modal='true' :visible.sync="show" width="35%" @close="close">
    <div ref="Dform" style="overflow-y:scroll;overflow-x:hidden;height:400px">
        <el-form :model="formData" ref="form" size="small" label-width="140px"  status-icon inline-message >
        <el-row v-for="(row,rowIndex) of rowItems" :key="'row'+rowIndex">
            <el-col :span="24" :key="index"  v-for="(item,index) of row" style="display: flex; flex-direction: row; align-items: center; min-height: ">
            <el-form-item  :label="item.name" :prop="item.prop" :rules="(item.required && (buttonEvent == 'edit()' || (buttonEvent == 'add()' && !item.disable)))?{ required: true, message: '请填写该字段', trigger: 'blur' }:null">
                <el-select v-if="item.type=='select'" v-model="formData[item.prop]" placeholder="请选择" :disabled="btnType=='detail'">
                <el-option v-for="(opitem,opindex) of item.options" :label="opitem.label" :value="opitem[item.optionValue?item.optionValue:'value']" :key="rowIndex+'_'+index+'_'+opindex"></el-option>
                </el-select>
                <el-input v-if="item.type=='text' || item.type=='textarea'"  v-model="formData[item.prop]" :type="item.type" :disabled="item.disable && btnType=='add'" :readOnly="btnType=='detail'|| item.readOnly" :placeholder="item.placeholder" :class="{'grayBack':btnType=='detail'|| item.readOnly}"></el-input>
                <el-checkbox v-if="item.type == 'checkbox'" :true-label="item.trueLabel" :false-label="item.falseLabel" v-model="formData[item.prop]" :checked="formData[item.prop] == 'true' || formData[item.prop] == 1 || formData[item.prop] == true" :disabled="item.disable && btnType=='add'" name="type" :readOnly="btnType=='detail'"></el-checkbox>
                <el-date-picker
                type="date" v-if="item.type == 'date'"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                v-model="formData[item.prop]"
                placeholder="选择日期" ></el-date-picker>
                <el-input v-if="item.type == 'search'"  :readonly="true" v-model="formData[item.proxy]">
                <el-button slot="append" icon="el-icon-search" @click="outSearch(rowIndex,index)"></el-button>
                </el-input>
                <el-input v-if="item.type == 'search'" type="hidden" v-model="formData[item.prop]" style="display: unset"/>
            </el-form-item>
            </el-col>
        </el-row>
        <el-row v-for="(row,rowIndex) of formData.orgPlanHierarchyDtoList" :key="'level'+rowIndex">
                <el-form-item  :label="'第 '+(rowIndex+1)+' 级'" :prop="'orgPlanHierarchyDtoList.'+rowIndex+'.nodeName'" :rules="{ required: true, message: '请填写该字段', trigger: 'blur' }">
                    <el-input  v-model="row.nodeName" type="text" placeholder="请输入层级名称"></el-input>
                </el-form-item>
                <el-button size="mini" v-if="row.pkid != null" @click="orgPlanHierarchy(row)">
                    <img src="/static/img/16/edit.png" style="vertical-align: text-bottom"/>
                    维护范围值
                </el-button>
                <el-button size="mini" type="danger" style="margin-right:5px" @click="delLevel(rowIndex)">
                    <img src="/static/img/16/delete.png" style="vertical-align: text-bottom;"/>
                    移除
                </el-button>
        </el-row>
        </el-form>
    </div>
    <div style="display:flex;justify-content:space-between;align-items:flex-end">
      <el-button style=" margin-top: 5px; margin-bottom: 10px;" @click="addLevel">
          <img src="/static/img/16/add.png" style="vertical-align: text-bottom"/>
          添加层级
      </el-button>
      <el-button style=" margin-top: 5px; margin-bottom: 10px;" type="primary" @click="submit">提 交</el-button>
    </div>
    <OrgPlanRangeEdit v-if="OrgPlanRangeEditShow" :hierarchy="hierarchy" @rangeEditShow="rangeEditShow" ></OrgPlanRangeEdit>
  </el-dialog>
</template>

<script>
  import http from '@/api/http'
  import {Message} from 'element-ui'
  import OrgPlanRangeEdit from "./OrgPlanRangeEdit"
    export default {
        name:'OrgPlanEdit',
        props:{
            addUrl:String,
            editUrl:String,
            originalData:Object,
            buttonEvent:String,
            items:Array
        },
        data() {
            return{
                formData:this.originalData,
                show: this.buttonEvent == 'detail()' || this.buttonEvent== 'add()' || this.buttonEvent== 'edit()',
                rowItems: [],
                btnType: '',
                OrgPlanRangeEditShow: false,
                hierarchy: {}
            }
        },
        methods:{
            close() {
              this.show = false
              this.$emit("editBack",null)
            },
            rangeEditShow (){
              this.OrgPlanRangeEditShow = false
            },
            refresh() {
                this.$emit("refresh")
            },
            setRowItems() {
              this.rowItems = []
              for (let i=0;i<this.items.length;i++) {
                  if (i%2==0) {
                      if (i+1<this.items.length){
                          this.rowItems.push([this.items[i],this.items[i+1]])
                      } else {
                          this.rowItems.push([this.items[i]])
                      }
                  }
              }
              this.getOptions()
              console.log(this.rowItems)
            },
            getOptions() {
                for (let i=0;i<this.rowItems.length;i++) {
                    for (let j=0;j<this.rowItems[i].length;j++) {
                        let temp = this.rowItems[i][j]
                        if (temp.type == 'select' && temp.optionsUrl) {
                            this.$http.get(temp.optionsUrl,{pageSize: temp.pagesize}).then(resp=>{
                                    if (resp instanceof Array) {
                                        temp.options = resp
                                    } else {
                                        temp.options = resp.list
                                    }
                                    for (let k=0;k<temp.options.length;k++) {
                                        temp.options[k].label = temp.options[k][temp.optionProxy]+(temp.optionAppendProxy?('['+temp.options[k][temp.optionAppendProxy]+']'):'')
                                    }
                                    this.$forceUpdate()
                            })
                        }
                    }
                }
            },
            setBtnType() {
                switch (this.buttonEvent) {
                    case this.$config.BTNS.ADD:
                        this.btnType = 'add'
                        break;
                    case this.$config.BTNS.EDIT:
                        this.btnType = 'edit'
                        break;
                    case this.$config.BTNS.DETAIL:
                        this.btnType = 'detail'
                        break;
                }
            },
            conditionChange() {
              this.$emit('conditionChange',null)
            },
            addLevel() {
                var that = this
                var level = {
                    nodeName: '',
                    isLast: 0,
                    num: this.formData.orgPlanHierarchyDtoList.length + 1
                }
                this.formData.orgPlanHierarchyDtoList.push(level);
                that.$nextTick(function(){
                    that.$refs.Dform.scrollTop = that.$refs.Dform.scrollHeight;
                });
                
            },
            delLevel(rowIndex) {
                this.formData.orgPlanHierarchyDtoList.splice(rowIndex,1)
            },
            /**新增架构主数据接口 */
            submit () {
              this.$refs.form.validate((valid) => {
                if (valid) {
                  //排查出最后一级
                  console.log(this.formData.orgPlanHierarchyDtoList)
                  for (let index = 0; index < this.formData.orgPlanHierarchyDtoList.length; index++) {
                    if (index == this.formData.orgPlanHierarchyDtoList.length - 1){
                      this.formData.orgPlanHierarchyDtoList[index].isLast = '1'
                    } else {
                      this.formData.orgPlanHierarchyDtoList[index].isLast = '0'
                    }
                    //此处需要将数组转换下，要不然后端识别不出
                    this.formData['orgPlanHierarchyDtoList[' + index + '].nodeName'] = this.formData.orgPlanHierarchyDtoList[index].nodeName
                    this.formData['orgPlanHierarchyDtoList[' + index + '].isLast'] = this.formData.orgPlanHierarchyDtoList[index].isLast
                    this.formData['orgPlanHierarchyDtoList[' + index + '].num'] = index + 1
                    this.formData['orgPlanHierarchyDtoList[' + index + '].pkid'] = this.formData.orgPlanHierarchyDtoList[index].pkid
                  }
                  //将此数组从对象中移除
                  this.$delete(this.formData,'orgPlanHierarchyDtoList')
                  console.log(this.formData)
                  if (this.formData.pkid !== undefined){
                    http.post(this.$api.API_ORG_ORGPLAN_UPDATE,this.formData)
                        .then(resp=>{
                        this.show = false
                        this.formData = null
                        Message({type: 'success', message: '保存成功'})
                        this.$emit("editBack",null)
                        this.conditionChange()
                    })
                  }else{
                    http.post(this.$api.API_ORG_ORGPLAN_ADD,this.formData)
                        .then(resp=>{
                        this.show = false
                        this.formData = null
                        Message({type: 'success', message: '保存成功'})
                        this.$emit("editBack",null)
                        this.conditionChange()
                    })
                  }
                } else {
                  this.$message.error('缺少字段')
                  return false;
                }
              });
            },
            /**查询层级列表 */
            findOrgPlanHierarchyList () {
              if (this.originalData.pkid !== undefined){
                http.get(this.$api.API_ORG_ORGPLAN_FINDORGPLANHIERARCHYLIST,{fkPlan:this.originalData.pkid})
                  .then(resp=>{
                    this.$set(this.formData,'orgPlanHierarchyDtoList',resp.list)
                })
              }else{
                this.$set(this.formData,'orgPlanHierarchyDtoList',[])
              }
            },
            /**层级范围值维护*/
            orgPlanHierarchy (item){
              this.hierarchy = item
              this.OrgPlanRangeEditShow = true
            }
        },
        mounted() {
        },
        created(){
          this.setRowItems()
          this.setBtnType()
          this.findOrgPlanHierarchyList()
        },
        components:{OrgPlanRangeEdit},
    }
</script>

<style lang="less" scoped>
.main-label{
    border: #ccc 1px solid;
    border-bottom: 0;
    height: 36px;
    line-height: 35px;
    font-weight: bold;
    padding-left: 5px;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .grid-content {
    min-height: 36px;
  }
  .head-btn{
    display: inline-flex;
    text-decoration: none;
    align-items: center;
    vertical-align: center;
    font: 8px/8px HelveticaNeue, Arial;
    padding: 0px 11px;
    border: 1px solid #FFF;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 9pt;
    margin-left: 2px;
    line-height: 25px;
    color: #000;
    outline: none;
    background-image: url(../../../assets/img/datagrid_header_bg.gif);
    background-repeat: repeat-x;
    border: 1px solid #ccc;
  &:hover {
     color: #FFF;
     filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#33bbee', endColorstr='#2288cc');
     border: 1px solid #d51900;
     background: linear-gradient(top, #d51900, #d51900);
     background: -moz-linear-gradient(top, #d51900, #d51900);
     background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#d51900), to(#d51900));
     text-shadow: -1px -1px 1px #1c6a9e;
   }
  /deep/span{
    display: block;
  }
  }

  /deep/.el-form-item__error {
    color: #F56C6C;
    font-size: 12px;
    line-height: 50px;
    position: absolute;
    padding: 0 5px !important;
    top: 0;
    left: 0;
  }
  /deep/.el-form-item {
    margin-bottom: 0px;
  }

  .el-row{
    display: flex;
    align-items: center;
    border: 1px solid #eee;
    .el-col:first-child{
      border-right: 1px solid #eee;
    }
    .grayBack{
      /deep/input,/deep/textarea{
        background: #f2f2f2;
      }
    }
  }

  /deep/.el-form-item__label {
    font-size: 12px;
  }
  /deep/.el-radio-button__inner {
    border-left: 1px solid #DCDFE6;
    font-weight: 600;
  }
  /deep/.el-input.is-disabled .el-input__inner {
    color: #606266;
  }
  /deep/.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
    margin-bottom: 0! important;
    display: flex;
    width: 100%;
    padding: 5px;
  }
  /deep/.el-form-item--small .el-form-item__label {
    padding: 0;
    margin-right: 5px;
    background: #f1f1f1;
    border: 1px solid #e7e7e7;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  /deep/.el-form-item--small .el-form-item__content {
    padding: 10px 10px;
    border: 1px solid #e7e7e7;
    align-items: center;
    height: 100%;
    flex-wrap: wrap;
    flex: 1;
    margin-left: 0px !important;
  }

  .info-label{
    padding: 10px 20px 10px 20px;
    display: inline-block;
    background-color: #d51900;
    margin-left: 5px;
    color: white;
    font-weight: bold;
  }
</style>